﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using JsonSharp;
using JsonSharp.Collections;
using JsonSharp.Values;
using Barbar.MapReport.Common;

namespace Barbar.MapReport.HtmlRender.Handlers {
  internal class MapCallbackHandler : ISimpleHttpHandler {
    #region ISimpleHttpHandler Members

    public void ProcessRequest(HttpContext context) {
      MapCallbackData callbackData = MapCallbackData.CreateMapCallbackData(context.Request.Form);
      JsonArrays result = new JsonArrays();
      foreach (string key in callbackData.Keys) {
        Type type = Type.GetType(key, true);
        MapCallbackService service = Activator.CreateInstance(type) as MapCallbackService;
        if (service == null)
          throw new MapReportException("Failed to create service (invalid type).");
        JsonObjects keyValuePair = new JsonObjects();
        keyValuePair.Add(new JsonStringValue("fnName"), new JsonStringValue(service.JavaScriptFunctionName));
        keyValuePair.Add(new JsonStringValue("arg"), service.ProcessCallback(callbackData));
        result.Add(keyValuePair);
      }
      context.Response.ContentType = "text/javascript";
      context.Response.Write(result.ToString());
    }

    #endregion
  }
}
